
from fastapi import FastAPI
from fastapi.responses import ORJSONResponse
from fastapi.middleware.cors import CORSMiddleware
from tortoise.contrib.fastapi import register_tortoise

from src.db.config import TORTOISE_CONFIG

from src.log import configure_logging
from src.settings import settings
from src.web.api.router import api_router
from src.web.lifespan import lifespan
def get_app() -> FastAPI:
    """Get FastAPI app
    
    This is the main constructor of an app.

    :return FastAPI: _description_
    """
    configure_logging()
    
    app = FastAPI(
        title=settings.app_name,
        version=settings.app_version,
        description=settings.app_description,
        default_response_class=ORJSONResponse,
        lifespan=lifespan,
    )
    
    # Configures routers
    app.include_router(router=api_router, prefix="/api")

    # Configures middlewares
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],  # 允许所有来源
        allow_credentials=True,
        allow_methods=["*"],  # 允许所有HTTP方法
        allow_headers=["*"]  # 允许所有请求头
    )
    
    
    # Configures tortoise orm
    register_tortoise(
        app,
        config=TORTOISE_CONFIG,
        add_exception_handlers=True,
    )
    
    return app